//
//  HomeViewController.m
//  RegBars
//
//  Created by Nhat on 7/26/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "HomeViewController.h"
#import "HomeCell.h"
#import "RestaurantDetailViewController.h"
#import "Restaurant.h"
#import "RegBarsAppDelegate.h"
#import "RegBarsAppDelegate_iPhone.h"
#import "RestaurantDetail.h"
#import "CitiesViewController.h"

#define kCustomRowHeight    83.0
#define kCustomRowCount     5

@implementation HomeViewController
@synthesize homeTable;
@synthesize titleView;
@synthesize leftView;
@synthesize centerView;
@synthesize rightView;
@synthesize titleBarBackground;
@synthesize specialTitleLabel;
@synthesize previousButton;
@synthesize nextButton;
@synthesize homeCell;
@synthesize loadingView;
@synthesize mondayDownloadsInProgress;
@synthesize currentLocation;
@synthesize myAddress;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (IBAction)backToCity:(id)sender{
//    [mainAppDelegate_iPhone.citiesViewController flipToHome];
}

- (IBAction)previousButtonPress{
    byScroll = NO;
	if (mainAppDelegate.date > 2) {
		[loadingView setHidden:NO];
		[self showPreviosView];
		mainAppDelegate.date--;
		[self loadRestaurant];
	} else {
        return;
		mainAppDelegate.date = 8;
		[self showPreviosView];
		[self loadRestaurant];
	}
}

- (IBAction)nextButtonPress{
    byScroll = NO;
	if (mainAppDelegate.date < 8) {
		[loadingView setHidden:NO];
		[self showNextView];
		mainAppDelegate.date++;
		[self loadRestaurant];
	} else{
        return;
		mainAppDelegate.date = 2;
		[self showNextView];
		[self loadRestaurant];
	}
//    [titleScrollView scrollRectToVisible:CGRectMake((mainAppDelegate.date - 2 )*200, 0, 200, 44) animated:YES];
}

- (void) showNextView{
    UIView *center = (UIView*)[viewArrays objectAtIndex:1];
    UIView *right = (UIView*)[viewArrays objectAtIndex:2];
    
    [UIView beginAnimations:nil context:NULL];
	[UIView setAnimationDuration:0.3f];
	CGRect frame = [center frame];
	frame.origin.x -= 320;
	[center setFrame:frame];
	[UIView commitAnimations];
	
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationDuration:0.3f];
	CGRect frameAnimate = [right frame];
	frameAnimate.origin.x += 320;
	[right setFrame:frameAnimate];
	[UIView commitAnimations];
    
    [self performSelector:@selector(updateRight) withObject:nil afterDelay:1];
}

- (void) showPreviosView
{
    UIView *left = (UIView*)[viewArrays objectAtIndex:0];
    UIView *center = (UIView*)[viewArrays objectAtIndex:1];
    
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationDuration:0.3f];
	CGRect frame = [center frame];
	frame.origin.x += 320;
	[center setFrame:frame];
	[UIView commitAnimations];
	
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationDuration:0.3f];
	CGRect frameAnimate = [left frame];
	frameAnimate.origin.x -= 320;
	[left setFrame:frameAnimate];
	[UIView commitAnimations];
    
    [self performSelector:@selector(updateLeft) withObject:nil afterDelay:1];
}

- (void) layout{
    UIView *left = (UIView*)[viewArrays objectAtIndex:0];
    [left setFrame:CGRectMake(-320, 0, 320, 416)];
    UIView *center = (UIView*)[viewArrays objectAtIndex:1];
    [center setFrame:CGRectMake(0, 0, 320, 616)];
    UIView *right = (UIView*)[viewArrays objectAtIndex:2];
    [right setFrame:CGRectMake(320, 0, 320, 416)];
    [homeTable removeFromSuperview];
    [center addSubview:homeTable];
    [homeTable setFrame:CGRectMake(0, 0, 320, 416)];
}

- (void) updateLeft{
    UIView *left = (UIView*)[viewArrays objectAtIndex:0];
    UIView *center = (UIView*)[viewArrays objectAtIndex:1];
    UIView *right = (UIView*)[viewArrays objectAtIndex:2];
    [viewArrays removeAllObjects];
    [viewArrays insertObject:center atIndex:0];
    [viewArrays insertObject:right atIndex:1];
    [viewArrays insertObject:left atIndex:2];
    [self layout];
}

- (void) updateRight{
    UIView *left = (UIView*)[viewArrays objectAtIndex:0];
    UIView *center = (UIView*)[viewArrays objectAtIndex:1];
    UIView *right = (UIView*)[viewArrays objectAtIndex:2];
    [viewArrays removeAllObjects];
    [viewArrays insertObject:right atIndex:0];
    [viewArrays insertObject:left atIndex:1];
    [viewArrays insertObject:center atIndex:2];
    [self layout];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [currentRestaurantList count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 83;
}
// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *homeCellId = @"HomeCellId";
    homeCell = (HomeCell*)[homeTable dequeueReusableCellWithIdentifier:homeCellId];
    if (homeCell == nil) {
        [[NSBundle mainBundle] loadNibNamed:@"HomeCell" owner:self options:nil];
    }
	Restaurant *restaurant = [currentRestaurantList objectAtIndex:[indexPath row]];
	//[homeCell.eventLabel setText:restaurant.eventDescription];
	NSArray *array = [restaurant.eventDescription componentsSeparatedByString:@", "];
	for (int i= 0; i< [array count]; i++) {
		[homeCell.eventTextView setText:[NSString stringWithFormat:@"%@ %@\n",homeCell.eventTextView.text,[array objectAtIndex:i]]];
	}
	if (!restaurant.thumbnail){
		if (homeTable.dragging == NO && homeTable.decelerating == NO){
			[self startIconDownload:restaurant forIndexPath:indexPath];
		}
		// if a download is deferred or in progress, return a placeholder image
		//feedCell.thumbnailImage.image = [UIImage newImageFromResource:@"feed_1.png"];                
	}
	else{
		homeCell.thumbnailImageView.image = restaurant.thumbnail;
		[homeCell.loadingView setHidden:YES];
	}
	
    return homeCell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
	if ([mainAppDelegate connectedToNetwork]) {
		if ([CLLocationManager locationServicesEnabled]) {
            Restaurant *restaurant = [currentRestaurantList objectAtIndex:indexPath.row];
//            NSLog(@"Selected Res Add: %@",restaurant.a);
            NSString *name = restaurant.nameTitle;
            name = [name uppercaseString];
            MyLocationParser *parser = [[MyLocationParser alloc] init];
            parser.delegate = self;
            //[parser findMyLocation:[NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/geocode/json?latlng=%f,%f&sensor=false",currentLocation.coordinate.latitude, currentLocation.coordinate.longitude]];
            [parser findMyLocation:[NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/geocode/json?latlng=49.023050,12.121000&sensor=false"]];//currentLocation.coordinate.latitude, currentLocation.coordinate.longitude]];
            [parser release];
            RestaurantDetail *restaurantDetail = [mainAppDelegate.restaurantDict objectForKey:[NSString stringWithFormat:@"%d",restaurant.restaurantId]];
            NSLog(@"restaurantId :%d - mainAppDelegate.restaurantDict :%@",restaurant.restaurantId,mainAppDelegate.restaurantDict);
            if (restaurantDetail) 
            {
                homeCell = (HomeCell*)[homeTable cellForRowAtIndexPath:indexPath];
//                RestaurantDetailViewController *controller = [[RestaurantDetailViewController alloc] init];
                mainAppDelegate_iPhone.resbarDetailController.startPoint = self.myAddress;
                mainAppDelegate_iPhone.resbarDetailController.endPoint = [NSString stringWithFormat:@"%@, %@, %@",restaurantDetail.address, restaurantDetail.city, restaurantDetail.phone];
                NSLog(@"restaurantDetail.address =%@",mainAppDelegate_iPhone.resbarDetailController.endPoint);
                mainAppDelegate_iPhone.resbarDetailController.restaurantDetail = restaurantDetail;
                mainAppDelegate_iPhone.resbarDetailController.restaurant = restaurant;
                mainAppDelegate_iPhone.resbarDetailController.currentLocation = self.currentLocation;
                mainAppDelegate_iPhone.resbarDetailController.title = restaurant.nameTitle;
                [self.navigationController pushViewController:mainAppDelegate_iPhone.resbarDetailController animated:YES];                
                mainAppDelegate_iPhone.resbarDetailController.restaurantThumbnail.image = homeCell.thumbnailImageView.image;
                for (int i = 0; i < [restaurantDetail.specialTime count]; i++) {
                    [mainAppDelegate_iPhone.resbarDetailController.timeTextView setText:[NSString stringWithFormat:@"%@ %@\n",mainAppDelegate_iPhone.resbarDetailController.timeTextView.text,[restaurantDetail.specialTime objectAtIndex:i]]];
                }
                [mainAppDelegate_iPhone.resbarDetailController update];
//                [controller release];
            } else{
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Message" message:@"Can not find the Bar at this time" delegate:nil cancelButtonTitle:@"Close" otherButtonTitles: nil];
                [alert show];
                [alert release];
            }
        } else {
            UIAlertView *alert  = [[UIAlertView alloc] initWithTitle:@"Message" message:@"Bitte Ortungsdienste aktivieren." delegate:nil cancelButtonTitle:@"Close" otherButtonTitles:nil];
            [alert show];
            [alert release];
        }
	}else {
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Message" message:@"Connot connect internet, please check your network connection" delegate:nil cancelButtonTitle:@"Close" otherButtonTitles:nil];
		[alert show];
		[alert release];
	}
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (void)didEndGetRestaurantForDate:(NSString*)keyDate restaurantArray:(NSArray *)Array{
    NSLog(@"didEndGetRestaurantForDate: %@",Array);
    [DSBezelActivityView removeViewAnimated:YES];
	[currentRestaurantList setArray:Array];
	[mondayDownloadsInProgress removeAllObjects];
	[homeTable reloadData];
	[loadingView setHidden:YES];
}

- (void) didEndFindMyLocation:(NSString*) address{
	[myAddress setString:address];
	NSLog(@"My adress = %@", myAddress);
}

#pragma mark -
#pragma mark Table cell image support
- (void)startIconDownload:(Restaurant*)restaurant forIndexPath:(NSIndexPath *)indexPath
{
    ImageDownloader *imageDownloader = [mondayDownloadsInProgress objectForKey:indexPath];
    if (imageDownloader == nil) {
        imageDownloader = [[ImageDownloader alloc] init];
        imageDownloader.restaurant = restaurant;
        imageDownloader.indexPathInTableView = indexPath;
        imageDownloader.delegate = self;
        [mondayDownloadsInProgress setObject:imageDownloader forKey:indexPath];
        [imageDownloader startDownload];
        [imageDownloader release];   
	}
}

// this method is used in case the user scrolled into a set of cells that don't have their app icons yet
- (void)loadImagesForOnscreenRows
{
    if ([currentRestaurantList count] > 0){
        NSArray *visiblePaths = [homeTable indexPathsForVisibleRows];
        for (NSIndexPath *indexPath in visiblePaths){
            Restaurant *restaurant = [currentRestaurantList objectAtIndex:indexPath.row];
            if (!restaurant.thumbnail){ // avoid the app icon download if the app already has an icon{
                [self startIconDownload:restaurant forIndexPath:indexPath];
			}
		}
	}
}

// called by our ImageDownloader when an icon is ready to be displayed
- (void)appImageDidLoad:(NSIndexPath *)indexPath
{
    ImageDownloader *imageDownload = [mondayDownloadsInProgress objectForKey:indexPath];
    if (imageDownload != nil){
        homeCell = (HomeCell*)[homeTable cellForRowAtIndexPath:imageDownload.indexPathInTableView];        
        // Display the newly loaded image
        homeCell.thumbnailImageView.image = imageDownload.restaurant.thumbnail;
		[homeCell.loadingView setHidden:YES];
	}
}

// Load images for all onscreen rows when scrolling is finished
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if (!decelerate){
        [self loadImagesForOnscreenRows];
	}
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    //    pageControlBeingUsed = NO;
    NSLog(@"Begin Scroll");
    byScroll = YES;
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if ([scrollView isEqual:titleScrollView]) {
        if (currentPage != newPage && byScroll) {
            NSLog(@"New page : %d Cur %d", newPage, currentPage);
            //do someting
            if (currentPage < newPage) {
                [self nextButtonPress];
            }else if(currentPage > newPage){
                [self previousButtonPress];
            }
            currentPage = newPage;
            //mainAppDelegate.date = currentPage+2;
            [self loadImagesForOnscreenRows];
        }
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)sender {
    // Update the page when more than 50% of the previous/next page is visible
    CGFloat pageWidth = titleScrollView.frame.size.width;
    newPage = floor((titleScrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
//    self.pager.currentPage = page;
    //    NSLog(@"Page : %d",page);
}

- (void) loadRestaurant{
    [DSBezelActivityView newActivityViewForView:self.view withLabel:@"loading..."];
	RestaurantParser *parser = [[RestaurantParser alloc] init];
	switch (mainAppDelegate.date) {
		case 2:{
			[parser getRestaurants:MondayURL withDelegate:self];
			[self.specialTitleLabel setText:Monday];
		}
			break;
		case 3:{
			[parser getRestaurants:TuesdayURL withDelegate:self];
			[specialTitleLabel setText:Tuesday];
		}
			break;
		case 4:{
			[parser getRestaurants:WednesdayURL withDelegate:self];
			[specialTitleLabel setText:Wednesday];
		}
			break;
		case 5:{
			[parser getRestaurants:ThursdayURL withDelegate:self];
			[specialTitleLabel setText:Thursday];
		}
			break;
		case 6:{
			[parser getRestaurants:FridayURL withDelegate:self];
			[specialTitleLabel setText:Friday];
		}
			break;
		case 7:{
			[parser getRestaurants:SaturdayURL withDelegate:self];
			[specialTitleLabel setText:Saturday];
		}
			break;
		case 8:{
			[parser getRestaurants:SundayURL withDelegate:self];
			[specialTitleLabel setText:Sunday];
		}
			break;
			
		default:
			break;
	}
	[parser release];
    [titleScrollView scrollRectToVisible:CGRectMake((mainAppDelegate.date - 2 )*200, 0, 200, 44) animated:YES];
//    byScroll = YES;?
}

- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation
{
	self.currentLocation = newLocation;
//	NSLog(@"%f", currentLocation.coordinate.latitude);
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle
- (void) dealloc{
    [homeTable release];
    [titleView release];
    [leftView release];
    [centerView release];
    [rightView release];
    [titleBarBackground release];
    [specialTitleLabel release];
    [previousButton release];
    [nextButton release];
    [viewArrays release];
	[currentRestaurantList release];
	[myAddress release];
    [super dealloc];
}

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
}
*/


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationItem.titleView = titleView;
    titleScrollView.delegate = self;
    titleScrollView.contentSize = CGSizeMake(1400, 44);
    currentPage = 0;
    newPage = 0;
    byScroll = NO;
    NSArray *titleArray = [NSArray arrayWithObjects:@"Specials Montag", @"Specials Dienstag",@"Specials Mittwoch",@"Specials Donnerstag",@"Specials Freitag",@"Specials Samstag",@"Specials Sonntag",nil];
    for (NSInteger i = 0; i < [titleArray count];i++) {
        NSString *string = [titleArray objectAtIndex:i];
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(200*i, 0, 200, 44)];
        [titleScrollView addSubview:label];
        label.text = string;
        [label setFont:[UIFont fontWithName:@"Helvetica" size:21.0f]];
        label.textColor = [UIColor whiteColor];
        label.backgroundColor = [UIColor clearColor];
        label.textAlignment = UITextAlignmentCenter;
        [label release];
    }
    [titleScrollView scrollRectToVisible:CGRectMake((mainAppDelegate.date - 2 )*200, 0, 200, 44) animated:YES];
    titleScrollView.showsHorizontalScrollIndicator = NO;
    currentPage = mainAppDelegate.date -2;
    self.myAddress = [[NSMutableString alloc] init];
	locationManager = [[CLLocationManager alloc] init];
	locationManager.delegate = self;
	locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move
	locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters; // 100 m
	[locationManager startUpdatingLocation];
	
	currentRestaurantList = [[NSMutableArray alloc] init];
	mondayDownloadsInProgress = [[NSMutableDictionary alloc] init];
    [self.view addSubview:leftView];
    [leftView setFrame:CGRectMake(-320, 0, 320, 416)];
    
    [self.view addSubview:rightView];
    [rightView setFrame:CGRectMake(320, 0, 320, 416)];
    
    [self.view addSubview:centerView];
    [centerView setFrame:CGRectMake(0, 0, 320, 416)];

    viewArrays = [[NSMutableArray alloc] initWithObjects:leftView, centerView,rightView, nil];
    [self.view addSubview:loadingView];
    [loadingView setFrame:CGRectMake(0, 0, 320, 416)];
    [loadingView setHidden:NO];
//    [self loadRestaurant];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    UIBarButtonItem *backButton = [[UIBarButtonItem alloc] 
                                   initWithTitle: @"zurück" 
                                   style: UIBarButtonItemStyleBordered
                                   target: nil action: nil];
    
    [self.navigationItem setBackBarButtonItem: backButton];
    [backButton release];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
